//
//  LWTabBar.swift
//  Microblog
//
//  Created by Roman on 17/1/4.
//  Copyright © 2017年 Roman. All rights reserved.
//

import UIKit

class LWTabBar: UITabBar {

    //定义闭包
    var composeClosure: (() -> ())?
    
    //初始化方法中添加子视图
    override init(frame: CGRect) {
        super.init(frame: frame)
        //中间添加按钮
        setupUI()
    }
    
    //解档的方法,xib/sb中加载的控制会调用该方法
    //重写了构造函数之后系统强制添加
    required init?(coder aDecoder: NSCoder) {
       // fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder) //支持Xib 的创建
        //中间添加按钮
        setupUI()
    }
    
    
   private func setupUI()  {
    
    self.addSubview(composeBtn)
    //监听按钮的点击
    composeBtn.addTarget(self, action: #selector(composeBtnClick), for: UIControlEvents.touchUpInside)
    
    }

    //按钮的点击事件希望外界能够访问吗?
    //@objc swift中默认会给所以继承自NSObject的类的对象或者方法隐式添加@objc动态标记,private私有的属性或者方法需要手动添加,当前这个方法就不具备动态特性
  @objc private func composeBtnClick()  {
        //执行闭包
        composeClosure?()
        
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        //获取子控件
        let width = UIScreen.main.bounds.width / 5
        let height = bounds.height
        
        //定义递增的索引
        var index = 0
        for subView in subviews {
            if subView.isKind(of: NSClassFromString("UITabBarButton")!){
                print(subView)
                subView.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: height)
                
//                if index == 1 {
//                    index += 1
//                }
//                index += 1
//                三目运算代替
                index += (index == 1 ? 2 : 1 )
            }
        }
        //设置撰写按钮的frame
        print(self.center)
        composeBtn.center = CGPoint(x: self.center.x, y: height * 0.5 )
        composeBtn.bounds.size = CGSize(width: width, height: height)
    }
    //MARK: 懒加载创建按钮,记得后面必须有括号
    lazy var composeBtn: UIButton = {
        let btn = UIButton(type: UIButtonType.custom)
        //设置图片
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        return btn
    }()

}
   





